package com.ruoyi.bizsys.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.bizsys.domain.AwardActConfigRelation;
import com.ruoyi.bizsys.domain.AwardActGroupRelation;
import com.ruoyi.bizsys.query.AwardActivityQuery;
import com.ruoyi.bizsys.service.IAwardActConfigRelationService;
import com.ruoyi.bizsys.service.IAwardActGroupRelationService;
import com.ruoyi.bizsys.vo.AwardActivityVO;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.bizsys.mapper.AwardActivityMapper;
import com.ruoyi.bizsys.domain.AwardActivity;
import com.ruoyi.bizsys.service.IAwardActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


/**
 * 奖励活动Service业务层处理
 *
 * @author african-loan
 * @date 2022-06-24
 */
@Service
@AllArgsConstructor
public class AwardActivityServiceImpl extends ServiceImpl<AwardActivityMapper, AwardActivity> implements IAwardActivityService {

    private final IAwardActConfigRelationService awardActConfigRelationService;
    private final IAwardActGroupRelationService awardActGroupRelationService;

    /**
     * 查询奖励活动
     *
     * @param id 奖励活动ID
     * @return 奖励活动
     */
    @Override
    public AwardActivity selectAwardActivityById(Long id) {
        return this.getById(id);
    }

    /**
     * 查询奖励活动列表
     *
     * @param awardActivity 奖励活动
     * @return 奖励活动
     */
    @Override
    public List<AwardActivity> selectAwardActivityList(AwardActivity awardActivity) {
        return this.list(new QueryWrapper<>(awardActivity).last("order by id desc"));
    }

    @Override
    public List<AwardActivityVO> selectAwardActivityList(AwardActivityQuery awardActivityQuery) {
        return baseMapper.selectAwardActivityList(awardActivityQuery);
    }

    @Override
    public AwardActivityVO selectById(Long id) {
        assert id != null && id != 0L : "id is null or 0L";
        AwardActivityQuery awardActivityQuery = new AwardActivityQuery();
        awardActivityQuery.setId(id);
        List<AwardActivityVO> list = baseMapper.selectAwardActivityList(awardActivityQuery);
        if (CollectionUtils.isEmpty(list)) {
            Map<String, String> map = new HashMap<>();
            map.put("id", String.valueOf(id));
            throw new BusinessException(RspEnmu.AWARD_ACT_IS_NOT_EXIST, map);
        }
        return list.get(0);
    }

    /**
     * 新增奖励活动
     *
     * @param awardActivity 奖励活动
     * @return 结果
     */
    @Override
    public int insertAwardActivity(AwardActivity awardActivity) {
        awardActivity.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(awardActivity);
    }

    @Override
    @Transactional
    public int insertAwardActivity(AwardActivityQuery awardActivityQuery) {
        int count = baseMapper.selectCount(new LambdaQueryWrapper<AwardActivity>()
                .eq(AwardActivity::getActType,awardActivityQuery.getActType())
                .eq(AwardActivity::getState,1));
        if(count>0){
            throw new BusinessException("活动已存在");
        }
        int i = baseMapper.insert(awardActivityQuery);
        this.processAwardActivityConfigRel(awardActivityQuery,true);
        this.processAwardActivityGroupRel(awardActivityQuery,true);
        return i;
    }

    @Override
    @Transactional
    public int updateAwardActivity(AwardActivityQuery awardActivityQuery) {
        assert awardActivityQuery.getId()!=null && awardActivityQuery.getId()!=0L : "id is null";
        int i = baseMapper.updateById(awardActivityQuery);
        this.processAwardActivityConfigRel(awardActivityQuery,false);
        this.processAwardActivityGroupRel(awardActivityQuery,false);
        return i;
    }

    @Override
    public int startAndStop(AwardActivityQuery awardActivityQuery) {
        assert awardActivityQuery.getId()!=null && awardActivityQuery.getId()!=0L : "id is null";
        return baseMapper.updateById(awardActivityQuery);
    }

    /**
     * 处理活动关联奖励配置
     * @param awardActivityQuery
     * @param isNew 新增的为true，不用remove处理
     */
    private void processAwardActivityConfigRel(AwardActivityQuery awardActivityQuery,boolean isNew){
        if("1".equals(awardActivityQuery.getActCondition()) && StringUtils.isEmpty(awardActivityQuery.getAwardConfigId())){
            throw new BusinessException(RspEnmu.AWARD_ACT_CONFIG_IS_NULL);
        }
        if(!isNew){
            awardActConfigRelationService.remove(new LambdaQueryWrapper<AwardActConfigRelation>()
                    .eq(AwardActConfigRelation::getActId,awardActivityQuery.getId()));
        }
        if(StringUtils.isEmpty(awardActivityQuery.getAwardConfigId())){
            return;
        }
        String[] awardConfigIds = awardActivityQuery.getAwardConfigId().split(",");
        List<AwardActConfigRelation> awardActConfigRelationList = new ArrayList<>();
        for (String awardConfigId : awardConfigIds) {
            AwardActConfigRelation awardActConfigRelation = new AwardActConfigRelation();
            awardActConfigRelation.setActId(awardActivityQuery.getId());
            awardActConfigRelation.setConfigId(Long.parseLong(awardConfigId));
            awardActConfigRelationList.add(awardActConfigRelation);
        }
        awardActConfigRelationService.saveBatch(awardActConfigRelationList);
    }

    /**
     * 处理活动关联参与者
     * @param awardActivityQuery
     * @param isNew 新增的为true，不用remove处理
     */
    private void processAwardActivityGroupRel(AwardActivityQuery awardActivityQuery,boolean isNew){
        if(!isNew){
            awardActGroupRelationService.remove(new LambdaQueryWrapper<AwardActGroupRelation>()
                    .eq(AwardActGroupRelation::getActId,awardActivityQuery.getId()));
        }
        if(StringUtils.isEmpty(awardActivityQuery.getAwardGroupId())){
            return;
        }
        String[] awardGroupIds = awardActivityQuery.getAwardGroupId().split(",");
        List<AwardActGroupRelation> awardActGroupRelationArrayList = new ArrayList<>();
        for (String awardConfigId : awardGroupIds) {
            AwardActGroupRelation awardActGroupRelation = new AwardActGroupRelation();
            awardActGroupRelation.setActId(awardActivityQuery.getId());
            awardActGroupRelation.setGroupId(Long.parseLong(awardConfigId));
            awardActGroupRelationArrayList.add(awardActGroupRelation);
        }
        awardActGroupRelationService.saveBatch(awardActGroupRelationArrayList);
    }


    /**
     * 修改奖励活动
     *
     * @param awardActivity 奖励活动
     * @return 结果
     */
    @Override
    public int updateAwardActivity(AwardActivity awardActivity) {
        awardActivity.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(awardActivity);
    }

    /**
     * 批量删除奖励活动
     *
     * @param ids 需要删除的奖励活动ID
     * @return 结果
     */
    @Override
    public int deleteAwardActivityByIds(Long[] ids) {
        assert ids!=null && ids.length!=0 : "ids is null";
        int i = baseMapper.deleteBatchIds(Arrays.asList(ids));
        //删除活动时删除外键关联关系
        awardActConfigRelationService.remove(new LambdaQueryWrapper<AwardActConfigRelation>()
                .in(AwardActConfigRelation::getActId,ids));
        awardActGroupRelationService.remove(new LambdaQueryWrapper<AwardActGroupRelation>()
                .eq(AwardActGroupRelation::getActId,ids));
        return i;
    }

    /**
     * 删除奖励活动信息
     *
     * @param id 奖励活动ID
     * @return 结果
     */
    @Override
    public int deleteAwardActivityById(Long id) {
        return baseMapper.deleteById(id);
    }

}
